package com.king.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.king.springcloud.entities.CommonResult;
import com.king.springcloud.entities.PaymentEntity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author king
 * @date 2020/10/20 16:33
 */
@RestController
public class CustomerController {
    @Resource
    private RestTemplate restTemplate;

    @Value("${service-url.nacos-user-service}")
    private String serverURL;

    @GetMapping("/consumer/fallback/{id}")
//    @SentinelResource(value = "fallback") // 没有配置
//    @SentinelResource(value = "fallback", fallback = "handlerFallback") // fallback只负责业务异常
//    @SentinelResource(value = "fallback", blockHandler = "blockHandler") // blockHandler 负责Sentinel控制台配置违规
//    @SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "blockHandler") // 未达到Sentinel违规标准则执行 fallback, 触发Sentinel则执行blockHandler
    @SentinelResource(value = "fallback", fallback = "handlerFallback", blockHandler = "blockHandler", exceptionsToIgnore = {IllegalArgumentException.class}) // 异常忽略
    public CommonResult fallback(@PathVariable("id")Long id){
        CommonResult result = restTemplate.getForObject(serverURL + "/paymentSQL/" + id, CommonResult.class);
        if (4L == id) {
            throw new IllegalArgumentException("IllegalArgumentException, 非法参数异常....");
        }else if(result.getData() == null){
            throw new NullPointerException("NullPointerException, 空指针异常....");
        }
        return result;
    }

    public CommonResult handlerFallback(@PathVariable("id")Long id, Throwable e){
        return new CommonResult(444, "兜底异常handlerFallback, 内容" + e.getLocalizedMessage(), new PaymentEntity(id, null));
    }

    public CommonResult blockHandler(@PathVariable("id")Long id, BlockException e){
        return new CommonResult(444, "兜底异常blockHandler, 内容" + e.getLocalizedMessage(), new PaymentEntity(id, null));
    }


}
